import 'package:flutter/services.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/bluetooth.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:quiver/strings.dart';
import '../../../generated/l10n.dart';

class UdtTbWorkreportrecordPrint extends StatefulWidget {
  UdtTbWorkreportrecordPrint();

  @override
  _UdtTbWorkreportrecordPrintState createState() =>
      _UdtTbWorkreportrecordPrintState();
}

class _UdtTbWorkreportrecordPrintState extends State<UdtTbWorkreportrecordPrint> {
  late var _subscription;

  late bool isLoading;

  var configList = [
    {
      "label": "零件编码",
      "key": "productCode"
    },{
      "label": "零件名称",
      "key": "productName"
    },{
      "label": "料厚/材质",
      "key": "productDes"
    },{
      "label": "总数量",
      "key": "sum"
    },
  ];
  Map<String,dynamic> data = {};
  num sum = 0.0;
  var qrCode = "";

  @override
  void initState() {
    super.initState();
    this.isLoading = isDisplayDesktop(Cry.context) ? false : true;
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecordPrint")
        .listen(_onEnvent);
  }

  @override
  void dispose() {
    StoreUtil.write("key", "workreportrecord");
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码后的结果
  void _onEnvent(dynamic obj) async {
    obj = obj["scan"];

    if (obj.contains("|")) {
      // 合单
      List objList = obj.split("|");
      var falg = await _getData(type: 2, barcode: objList[1]);
      if (falg != null) {
        return;
      }
      List orderList = objList[0].split(";");
      for (var i = 0; i < orderList.length; i++) {
        await _getData(
          type: 1,
          barcode: orderList[i],
        );
      }
      data["sum"] = sum.toString();
      qrCode = obj;
      isLoading = false;
      setState(() {});
    }else{
      CryUtils.message("请扫描工艺流程卡");
    }
  }

  _getData({int? type, String? barcode, bool? isLast}) async {
    // todo type代表不同的对象（1：生产单号；2：人员；3：产品；）
    if (isBlank(barcode)) {
      return;
    }
    try {
      if (type == 1) {
        // todo 产品单号
        var res = await HttpUtil.get(
            "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanInfo?PlanId=$barcode");
        if (!res.success! || res.data.length == 0) {
          CryUtils.message("$barcode生产单号不存在！");
          return;
        }
        num planQTY = _getPlanQTY(
            res.data[0]["PlanItems"], data["productCode"].toString());
        if (planQTY == -1) {
          CryUtils.message(
              "$barcode生产单号下没有${data["productCode"]}产品！");
          return;
        }
        // 添加合格数
        sum += planQTY;
        return;
      }
      if (type == 2) {
        ResponseBodyApi res = await DynamicDataApi.getModels(
            model: "product.template", key: 'default_code', val: barcode);
        if (res.success!) {
          if (res.data.length == 0) {
            CryUtils.message("$barcode零件图号不存在");
            return "";
          } else if (res.data.length > 1) {
            CryUtils.message("$barcode零件图号重复");
            return "";
          } else {
            if (barcode == data["productCode"]) {
              return "";
            }
            print(data);
            data = {};
            sum = 0;
            data["productCode"] = res.data[0]["default_code"] != false
                ? res.data[0]["default_code"].toString()
                : "";
            data["productName"] = res.data[0]["name"] != false
                ? res.data[0]["name"].toString()
                : "";
            data["productDes"] = res.data[0]["description"] != false
                ? res.data[0]["description"].toString()
                : "";
          }
        }
      }
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return "";
    }
  }

  num _getPlanQTY(List list, String productCode) {
    for (var element in list) {
      if (element["ProductSpec"] == productCode) {
        return element["PlanQTY"];
      }
    }
    return -1;
  }

  @override
  Widget build(BuildContext context) {

    var result = isLoading?Scaffold(
      appBar: AppBar(
        title: Text("扫码"),
      ),
      body: Container(
        width: 650,
        height: 650,
        color: Colors.black87,
        child: Center(
          child: Text(
            "请扫描工艺流程卡",
            style: TextStyle(fontSize: 36, color: Colors.red),
          ),
        ),
      ),
      // bottomNavigationBar: buttonBar,
    ): BluetoothView(data: data, configList: configList, qrCode:qrCode,);
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
